var Geppeto = Geppeto || {};

var gadgetName = "TokenOffice";

(function () {
/******************************************************************************/

/**
 * Disable default browser right click menu.
 */
document.oncontextmenu = function (e) {
  disableDefaultContextMenu(e);
};


function disableDefaultContextMenu(e) {
  // Mozilla Firefox, Google Chrome
  if (e && e.stopPropagation) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
  // Internet Explorer
  else if (window && window.event) {
    window.event.returnValue = false;
  }
};


/**
 * Wait for all elements to load completely.
 */
geppeto.CrossBrowser.addEventListener(window, "load", geppetoContextMenuTriggerInit, false);

//check if geppeto is available	
window.addEventListener("load", function() {
			test_geppeto_availability();
	}, false);	


function geppetoContextMenuTriggerInit() {
  // Execute on all gadgets except Geppeto gadgets
  if (/*document.getElementById("geppetoLogo") == null*/true) {
    var allElements = document.getElementsByTagName("*");
    var selectedElement = {};
    for(var i=0; i<allElements.length; i++) {
      geppeto.CrossBrowser.addEventListener(allElements[i], "mousedown", function(e) {
        // on right click, geppeto context menu is fired on container
        if (geppeto.CrossBrowser.getMouseButton(e) == 2) {
          var mouseTarget = geppeto.CrossBrowser.getTarget(e);
          var names = new Names(null);
          selectedElement.name = names.genXPathExpr(mouseTarget);
          selectedElement.url = getGadgetSpecUrl();
          selectedElement.containerName = "";
          selectedElement.parentId = mouseTarget.parentNode.id;
          selectedElement.outerHTML = Geppeto.Util.getOuterHTML(mouseTarget);
          selectedElement.sourceGadget = window.name;
          selectedElement.description = Geppeto.Util.getElementDescription(mouseTarget);
          var contextMenuCoordinates = calculateGeppetoContextMenuCoordinates(e);
          
          // key for context menu filtering
          var filterKey = geppeto.CrossBrowser.getTargetType(e);
          if (filterKey == null) {
            filterKey = geppeto.CrossBrowser.getTargetNodeName(e);
          }

          gadgets.rpc.call("", "showGeppetoContextMenu", null,
                           contextMenuCoordinates, selectedElement,
                           filterKey, true);
        }else if ((geppeto.CrossBrowser.getMouseButton(e) == 0) && (Interpreter.recordingMode == true)){
					//recording mode handler (TriggerMe, TickMe)
					
					var mouseTarget = geppeto.CrossBrowser.getTarget(e);
					if (mouseTarget.click){
						var names = new Names(null);
						selectedElement.name = names.genXPathExpr(mouseTarget);
						selectedElement.url = getGadgetSpecUrl();
						selectedElement.containerName = "";
						selectedElement.parentId = mouseTarget.parentNode.id;
						selectedElement.outerHTML = Geppeto.Util.getOuterHTML(mouseTarget);
						selectedElement.sourceGadget = window.name;
						selectedElement.description = Geppeto.Util.getElementDescription(mouseTarget);
						
						gadgets.rpc.call('',"sendTargetData",null,selectedElement);
					}
				}
        geppeto.CrossBrowser.stopPropagation(e);
      }, false);
    }

    // hide right-click menu with normal click
    geppeto.CrossBrowser.addEventListener(document, "click", function(e) {
      if (geppeto.CrossBrowser.getMouseButton(e) == 0) {
        gadgets.rpc.call("", "hideGeppetoContextMenu", null);
        geppeto.CrossBrowser.stopPropagation(e);
      }
    }, false);
  }
};


Geppeto.geppetoContextMenuTriggerInit = geppetoContextMenuTriggerInit;


function calculateGeppetoContextMenuCoordinates(e) {
//  if (!e.target.offsetParent){
//    return null;
//  }
  
  // Internet Explorer
  if (e == null) {
    e = window.event;
  }
  
  return [e.clientX, e.clientY];
};

/******************************************************************************/
}) ();

var selectedButton; // reference to selected action button 

var TARGET_NONE = ""; // constant for target_module_ids and target_xpaths for NOP actions

// value sent in the 'handleContextUI' for the click option in the Geppeto context menu
var MENU_OPTION_CLICK = "click";

var CONTAINER_ID = ""; // container ID for RPC calls
var LOCAL_MODULE_ID = _args()["mid"]; // a string representing a number (e.g. "30")


var prefs; //user prefrs

var target_xpaths; //contains target gadget xpath
var target_module_ids; //contains target gadget module id
var g_name;
var g_element;
var muted; // actions are executed on event occurence ("true" or "false")

//status messages

var INIT = "Starting gadget";
var GET_LIST = "Loading event list";
var GET_DETAILS = "Loading events";

// TriggerMe.signalEvent = function(evData){
	// if (muted == "false"){
		// var evID = evData.split('-');
		// evID.splice(0,1);
		// evID = evID.join('-');
		
		// var elem = document.getElementById(evID);
		// executeAction(elem.getElementsByTagName("td")[1]);
	// }
// }

function executeAction(element) {
	/* Called when an event occurs
	 * clicks on the element on remote gadget
	 *
	 */
	//Ovo je hardkodiranje, jer mi treba da radi i to sutra
	element = document.getElementById('odaziv');
	//if ( !(element.outerHTML.indexOf("module_id")) )
	//    return;
	var module_id = element.getAttribute("module_id");
	var xpath = element.getAttribute("xpath");
	if (module_id && module_id!==TARGET_NONE) {
		if (element.style.backgroundColor.toString() == "lightgreen"){
			element.style.backgroundColor = "orange";
		}else{
			element.style.backgroundColor = "lightgreen";
		}
		gadgets.rpc.call(get_remote_iframe_id(module_id),"clickElement",null,xpath);
		//HERE I added code to remove action after it fires
		if (selectedButton && selectedButton.getAttribute("module_id") != TARGET_NONE){
			//Ova prva mi je smetala, jer mi zbog tog nije mogao za novi token
			// primijenit staru akciju
			//selectedButton.setAttribute("module_id", TARGET_NONE);			
			
			//A ovo, je katastrofa, ima dva == dakle to nije radilo nista
			//CURRENT_ACTION_STATE = selectedButton.value == "Nije izabran";
		}
	}
	
	
}

var avail_timeout = 100; // time in ms to wait between probing for Geppeto
var avail_maxtries = 10; // maximum number of probes before it is assumed Geppeto is not installed
var avail_tries = 0;
function test_geppeto_availability() {
  /*
   * Equates Geppeto availabilty with the RPC module being loaded into this gadget's frame.
   * Parametrized by avail_timeout and avali_maxtries.
   */
			 
  if (avail_tries >= avail_maxtries) {
  //  Geppeto unavailable
  } else {
	avail_tries += 1;
	if (gadgets.rpc !== undefined) {

	  // register RPC services
		gadgets.rpc.register('handleGeppetoContextMenu', handleGeppetoContextMenu);
		gadgets.rpc.register('Geppeto.Gadget.setFocus', setFocus);	

	  //GIFPC.register('signalEvent',TriggerMe.signalEvent);
		
	  //Attach focus handler
	  var thisModuleId = _args()['mid'];
	  gadgets.rpc.call('','atachGeppetoFocusHandler',null,thisModuleId);
					
	} else {
	  window.setTimeout(test_geppeto_availability, avail_timeout);
	}
  }
}

	
var ODAZIV_SELECTED = "Izabran!";
var USER_INSTRUCTION = "Zadaj odaziv...";
var CURRENT_ACTION_STATE = "Nije izabran"; //
function setFocus(focus) {
	inFocus = focus;
	
	if (inFocus == false){				 
		if (selectedButton && selectedButton.value == USER_INSTRUCTION){
			gadgets.rpc.call('', 'setRecordingMode', null, false);
			recording = false;
			if (selectedButton.getAttribute("module_id") != TARGET_NONE){
				selectedButton.value = CURRENT_ACTION_STATE;//"Click "+selectedButton.getAttribute("g_element")+" at "+selectedButton.getAttribute("g_name");
			}else{
				selectedButton.value = CURRENT_ACTION_STATE;
			}
		}
	}
}


var inFocus = false;
var recording = false;
function set_action(e) {
  /*
   * Onclick handler for Action buttons.
   * Stores the clicked button info so it can later be 
   * linked to the external button.
   */ 
   var target = get_event_target(e);
   //doTheWhenClicked(target);   
}

function doTheWhenClicked(target){
  if(inFocus){
		//#Try 1
		// if (selectedButton && selectedButton.value == USER_INSTRUCTION){
		// //...#Try 2 
		   // User clicked twice on the same button, wants to exit recording mode
		   // I should return 'odaziv' button to initial value value="Nije izabran"
		
			// if (selectedButton.getAttribute("module_id") != TARGET_NONE){
				// selectedButton.value = "Click "+selectedButton.getAttribute("g_element")+" at "+selectedButton.getAttribute("g_name");
				// //HERE I did not add token dependant code
				// // if (selectedButton.id = 'odaziv'){
					// // token._hasHelloAction = 1;
				// // }
			// }else{
				// selectedButton.value = "Click";
			// }
		// }
		selectedButton = target;
		CURRENT_ACTION_STATE = selectedButton.value =USER_INSTRUCTION;	
		//HERE I make it visible to the user that it is recodrding
		//I could change font
	} else{
		alert("Warning!\nCan not set action, gadget out of focus.");
	}

	if (inFocus && !recording){
		recording = true;
		gadgets.rpc.call('', 'setRecordingMode', null, true);
	}
}
		
function get_event_target(e) {
  /*
   * Returns the target DOM element of the event 'e'.
   * Copied from w3schools.
   */
  var target;
  if (!e) {
		var e = window.event;
  }
  if (e.target) {
		target = e.target;
  } else if (e.srcElement) {
		target = e.srcElement;
  }
  if (target.nodeType === 3) { // Safari bug
		target = target.parentNode;
  }
  
  return target;
}
		
function handleGeppetoContextMenu(selectedMenuItemId, selectedElement, gadgets_list) {
  /*
   * Handles 'handleGeppetoContextMenu' messages from the container.
   * Stores information about the target element if and only if
   * menu_option equals MENU_OPTION_CLICK.
   * Only allows click actions on elements of other gadgets.
   */
								
	if (recording && inFocus && selectedMenuItemId === MENU_OPTION_CLICK){
	
		//resolve source gadget name
		var tempContainerName = "";
		var thisContainerName = Geppeto.Environment.remoteIdPrefix + _args()["mid"];
		if (thisContainerName == selectedElement.sourceGadget && gadgetName) {
			tempContainerName = gadgetName;
		}
		else {
			for (var gadget in gadgets_list) {
				if (gadgets_list[gadget].specUrl == selectedElement.url) {
					selectedElement.containerName = gadgets_list[gadget].title;
					break;
				}
			}
			// Remove all the blanks from containerName.
			tempContainerName = selectedElement.containerName;
		}
		
		if (tempContainerName == ""){
			tempContainerName = "Unknown";
		}
		
		var element_name = selectedElement.description;
		if (element_name == "") {
			element_name = "Element";
		}
		
		if (selectedElement.name == ""){
			alert("Warning!\nAction not set, invalid element name");
		}
		
		zdravo=document.getElementById('zdravo');
		//
		if (selectedButton.id == 'odaziv' && document.getElementById('pickComingAction').style.display == "none") {		
			zdravo.setAttribute("module_id", selectedElement.sourceGadget.split('_')[2]); 
			zdravo.setAttribute("xpath", selectedElement.name);						
			zdravo.setAttribute("g_name", tempContainerName);
			zdravo.setAttribute("g_element", element_name);
			selectedButton.setAttribute("module_id", selectedElement.sourceGadget.split('_')[2]); 
			selectedButton.setAttribute("xpath", selectedElement.name);						
			selectedButton.setAttribute("g_name", tempContainerName);
			selectedButton.setAttribute("g_element", element_name);
			}
		else
		{
			selectedButton.setAttribute("module_id", selectedElement.sourceGadget.split('_')[2]); 
			selectedButton.setAttribute("xpath", selectedElement.name);						
			selectedButton.setAttribute("g_name", tempContainerName);
			selectedButton.setAttribute("g_element", element_name);
		}
		//HERE I will show whole action in title, and for my buttons I will shorten the displayed text
		selectedButton.setAttribute("title", "Click "+element_name+" at "+tempContainerName);
        document.getElementById('clearAction').style.display = "inline";
		document.getElementById('clearAction2').style.display = "inline";
		//HERE I added token dependant code
		if (selectedButton.id == 'odaziv' || selectedButton.id == 'zdravo'){
			token._hasHelloAction = 1;
			CURRENT_ACTION_STATE = selectedButton.value = ODAZIV_SELECTED;
			//staviti u oba gumba
			zdravo.value = CURRENT_ACTION_STATE;
			
		} //This is for all the rest, value is as it was diplayed before
		else {
			selectedButton.value = "Click "+element_name+" at "+tempContainerName;
		}
		//Make button text wrap
		selectedButton.style.whiteSpace = "normal";

		// var index = selectedButton.getAttribute("index");
		// target_xpaths[index] = selectedElement.name;
		// target_module_ids[index] = selectedElement.sourceGadget.split('_')[2];
		// g_name[index] = tempContainerName;
		// g_element[index] = element_name;
		
		//TriggerMe.saveActionState();
		gadgets.rpc.call('', 'setRecordingMode', null, false);
		recording = false;		
		return;
	}
	
    //This chunk will start recording mode	
	if (inFocus && selectedMenuItemId === "whenClicked"){
		var thisContainerName = Geppeto.Environment.remoteIdPrefix + _args()["mid"];
		if (thisContainerName == selectedElement.sourceGadget) {
				//Here I added token dependant code
				if (selectedElement.description == "Odazovi se!")
				{
					document.getElementById('zdravo').value = USER_INSTRUCTION;
				}
				if (selectedElement.description == "Nije izabran" || selectedElement.description == "Izabran!"
                   || selectedElement.description == "Zadaj odaziv..." 
				   || selectedElement.description == "Odazovi se!"){
					//#Try 1 CRITICAL
					// Ovdje on prek interpretera klikne na gumb koji je programirljiv
					// i onda se pozove ona set_action(e) fja koja 
					//	omogucava programiranje gumba na obican click
					//A JA TO NE ZELIM, JA ZELIM ISKLJUCIVO KROZ IZBORNIK
					//Interpreter.clickElement(selectedElement.name);
					
					// Odkomentiraj dolje, ako zelis na When clicked ponistiti prethodno ukodiranu akciju 
					// Buduci da sad ne zelim u geppetoContextMenu dodavati opciju "Dismiss" ili "Cancel"
					// onda cu napravit da se prethodno ukodirana akcija izbrise svaki put kad 
					// se klikne na "When clicked..."
                    
                    //Zakomentira jer sam dodao Cancel ispod gumba
					// odaziv = document.getElementById('odaziv');
					// odaziv.setAttribute("module_id", ""); 
					// odaziv.setAttribute("xpath", "");						
					// odaziv.setAttribute("g_name", "");
					// odaziv.setAttribute("g_element", "");
					// odaziv.setAttribute("style", "width:100px");
					// odaziv.setAttribute("title", "");

					doTheWhenClicked(odaziv);
				}				
		}
		return;
	}
				
	//Else, some other option was clicked that is not allowed
	if(recording && inFocus){
		alert('This option is not supported');
		gadgets.rpc.call('', 'setRecordingMode', null, false);
		recording = false;		
		//CURRENT_ACTION_STATE = document.getElementById('odaziv').value = "Nije izabran";
		//token._hasHelloAction = 0;
	}
	else
	   alert('This option is not supported');
}
		
		
function module_id_from_iframe_id(iframe_id) {
  /*
   * Returnes the module ID as a string representing a number (e.g. "30").
   * Assumes iframe IDs are formated as a series of strings separated by 
   * underscores, with the last element being the module ID (e.g. remote_iframe_30)
   */
  var values = iframe_id.split("_");
  return values[values.length - 1];
}
		
		
function get_remote_iframe_id(module_id) {
  /*
   * Returns a valid iframe ID based on the specified module ID.
   * module_id should be a number represented as a string (e.g. "30")
   */
  return "remote_iframe_" + module_id;
}
		
function highlight_target(e) {
  /*
   * If a target for the outcome specified by the event 'e' is defined, 
   * requests a highlight via a RPC 'highlightElement' message.
   * Also highlights the outcome "button" with GeppetoHighlighter.highlight
   */
  var target = get_event_target(e);
			var module_id = target.getAttribute("module_id");
			var xpath = target.getAttribute("xpath");
			
  if (module_id && module_id!==TARGET_NONE) {
	gadgets.rpc.call(get_remote_iframe_id(module_id), "highlightElement",null,xpath);
	Interpreter.Highlighter.highlight(target);
  }
}
		
function unhighlight_target(e) {
  /*
   * Checks if there is an action asociated with the event 'e', and (if there is) 
   * sends a 'unhighlightLastElement' message to the remote gadget and relies on
   * GeppetoHighlighter.unhighlight to remove highlighting from the local button.
   */
  var target = get_event_target(e);
			var module_id = target.getAttribute("module_id");
			var xpath = target.getAttribute("xpath");
			
  if (module_id && module_id!==TARGET_NONE) {
	gadgets.rpc.call(get_remote_iframe_id(module_id), "unhighlightLastElement",null,xpath);
	Interpreter.Highlighter.unhighlight();
  }
}

var geppetoExtension = "loaded";

